﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Fee.FileAttachs;
using Fee.IO.Importers;
using Fee.Orders;
using Fee.Stores;
using JwtWebApi.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Ornament.ImportHelper;

namespace JwtWebApi.Controllers
{
    [Authorize]
    [Route("[controller]")]
    [ApiController]
    [EnableCors]
    public class ImportorController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly FileManager _fileManager;


        private readonly IVendorMatcherStore<ApplicationDbContext> _vendorMatcherStore;


        public ImportorController(ApplicationDbContext context, FileManager fileManager,
            IVendorMatcherStore<ApplicationDbContext> vendorMatcherStore
            , DelegateOrderBatchGenerator orderBatchGenertor
        )
        {
            _context = context;
            _fileManager = fileManager;
            _vendorMatcherStore = vendorMatcherStore;
        }


        [HttpPost("Import/{type}")]
        public async Task<IActionResult> Post([FromForm] IFormFile formFile, [FromRoute] string type)
        {
            // full path to file in temp location
            var filePath = _fileManager.GetTempPrivateFile(Path.GetExtension(formFile.FileName), User.Identity);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }

            var importRowResults = GetImportManager(type, filePath, out var resultFilePath, out var isValidate);

            var message = isValidate ? "导入成功" : "导入失败";
            message += "。请点击结果文件，查看文件导入结果";

            return Json(new
            {
                successed = isValidate,
                resultFilePath,
                message
            });
        }


        [HttpGet("download")]
        public IActionResult GetBlobDownload([FromQuery] string link)
        {
            var filePath = Path.Combine(_fileManager.GetPrivateTempFolder(User.Identity), link);
            var contentType = "application/octet-stream";
            var fileName = link;
            return File(System.IO.File.OpenRead(filePath), contentType, fileName);
        }

        private IList<ImportResultItem> GetImportManager(string type, string filePath, out string resultFilePath,
            out bool isValidate)
        {
            IImportor manager;
            type = type.ToUpper();
            switch (type)
            {
                case "PROJECT":
                    manager = new ProjectImporter<ApplicationDbContext>(_context);
                    break;
                case "VENDORMATCHER":
                    manager = new VendorMatcherImporter<ApplicationDbContext>(_context, _vendorMatcherStore);
                    break;
                case "FRAMEWORKCONTRACT":
                    manager = new FrameworkImporter<ApplicationDbContext>(_context);
                    break;


                default:
                    throw new NotImplementedException(type + " not implement");
            }

            isValidate = manager.Import(filePath, out var rowResults, out resultFilePath);
            return rowResults;
        }
    }
}